import { ref, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { Modal } from 'ant-design-vue'
import type { TablePaginationConfig } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue/es/form'
import type { Key } from 'ant-design-vue/es/table/interface'
import type { DictType } from '@/types/api/config/dictType'
import type { DictData } from '@/types/api/config/dictData'
import { useDictStore } from '@/stores/config/dict'
import { storeToRefs } from 'pinia'

/**
 * 字典管理业务逻辑钩子函数
 */
export default function useDictManagement() {
  // ------------ 国际化和工具引入 ------------
  const { t } = useI18n()
  
  // ------------ 使用状态管理 ------------
  const dictStore = useDictStore()
  
  // 从store中提取响应式状态
  const {
    // 基础状态
    currentDictType,
    currentDictTypeName,
    
    // 加载状态
    typeLoading,
    typeSubmitLoading,
    dataLoading,
    dataSubmitLoading,
    
    // 字典类型状态
    typeList,
    typePagination,
    typeQueryParams,
    createTimeRange,
    typeModalVisible,
    typeFormData,
    typeFormTitle,
    
    // 字典数据状态
    dataList,
    dataPagination,
    dataQueryParams,
    dataModalVisible,
    dataFormData,
    dataFormTitle
  } = storeToRefs(dictStore)
  
  // ------------ 组件引用 ------------
  const typeFormRef = ref<FormInstance>()
  const dataFormRef = ref<FormInstance>()

  // ------------ 基础状态 ------------
  // Tab切换
  const activeTab = ref<string>('type')
  
  // 错误处理状态
  const typeLoadError = ref<boolean>(false)
  const typeErrorMessage = ref<string>('')
  const dataLoadError = ref<boolean>(false)
  const dataErrorMessage = ref<string>('')
  
  // ------------ 字典类型状态 ------------
  // 表格选择行
  const typeSelectedRowKeys = ref<Key[]>([])
  
  // ------------ 字典数据状态 ------------
  // 表格选择行
  const dataSelectedRowKeys = ref<Key[]>([])
  
  // ------------ 格式化参数方法 ------------
  /**
   * 获取类型搜索表单参数
   */
  const typeSearchForm = computed(() => ({
    dictName: typeQueryParams.value.dictName || '',
    dictType: typeQueryParams.value.dictType || '',
    status: typeQueryParams.value.status,
    createTime: createTimeRange.value
  }))
  
  /**
   * 获取数据搜索表单参数
   */
  const dataSearchForm = computed(() => ({
    dictType: dataQueryParams.value.dictType || '',
    dictLabel: dataQueryParams.value.dictLabel || '',
    dictValue: dataQueryParams.value.dictValue || '',
    status: dataQueryParams.value.status
  }))
  
  // ------------ 字典类型方法 ------------
  /**
   * 加载字典类型数据
   */
  const loadTypeData = async () => {
    try {
      typeLoadError.value = false
      typeErrorMessage.value = ''
      
      await dictStore.fetchTypeList()
      
      // 检查数据是否为空
      if (typeList.value.length === 0) {
        typeErrorMessage.value = t('dict.emptyData')
      }
    } catch (error: any) {
      typeLoadError.value = true
      typeErrorMessage.value = error?.message || t('dict.loadFailed')
    }
  }

  // 查询
  const handleTypeSearch = () => {
    typeQueryParams.value.pageNum = 1
    loadTypeData()
  }

  // 重置查询表单
  const resetTypeSearch = () => {
    dictStore.resetTypeQuery()
    loadTypeData()
  }

  // 表格变化事件
  const handleTypeTableChange = (pag: TablePaginationConfig) => {
    dictStore.handleTypePageChange(pag.current || 1, pag.pageSize)
  }

  // 多选变化
  const onTypeSelectChange = (keys: Key[]) => {
    typeSelectedRowKeys.value = keys
  }

  // 新增
  const handleAddType = () => {
    dictStore.openTypeModal()
  }

  // 编辑
  const handleEditType = (record: DictType) => {
    dictStore.openTypeModal(record.id)
  }

  // 提交表单
  const handleTypeModalOk = async () => {
    await dictStore.submitTypeForm()
  }

  // 删除
  const handleDeleteType = async (record: DictType) => {
    Modal.confirm({
      title: t('common.confirm'),
      content: t('dict.deleteDataConfirm'),
      okText: t('common.confirm'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      async onOk() {
        await dictStore.removeType(record.id)
      }
    })
  }

  // 批量删除
  const handleBatchDeleteType = async () => {
    if (typeSelectedRowKeys.value.length === 0) {
      return
    }
    Modal.confirm({
      title: t('common.confirm'),
      content: t('dict.batchDeleteConfirm'),
      okText: t('common.confirm'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      async onOk() {
        const success = await dictStore.batchRemoveType(typeSelectedRowKeys.value as string[])
        if (success) {
          typeSelectedRowKeys.value = []
        }
      }
    })
  }

  // 导出字典类型
  const handleExportType = async () => {
    await dictStore.exportType()
  }

  // 查看字典数据
  const handleViewData = (record: DictType) => {
    dictStore.setCurrentType(record.dictType, record.dictName)
    activeTab.value = 'data'
  }

  // ------------ 字典数据方法 ------------
  /**
   * 加载字典数据数据
   */
  const loadDataData = async () => {
    if (!currentDictType.value) return
    
    try {
      dataLoadError.value = false
      dataErrorMessage.value = ''
      
      await dictStore.fetchDataList()
      
      // 检查数据是否为空
      if (dataList.value.length === 0) {
        dataErrorMessage.value = t('dict.emptyData')
      }
    } catch (error: any) {
      dataLoadError.value = true
      dataErrorMessage.value = error?.message || t('dict.loadFailed')
    }
  }

  // 查询
  const handleDataSearch = () => {
    dataQueryParams.value.pageNum = 1
    loadDataData()
  }

  // 重置查询表单
  const resetDataSearch = () => {
    dictStore.resetDataQuery()
    loadDataData()
  }

  // 表格变化事件
  const handleDataTableChange = (pag: TablePaginationConfig) => {
    dictStore.handleDataPageChange(pag.current || 1, pag.pageSize)
  }

  // 多选变化
  const onDataSelectChange = (keys: Key[]) => {
    dataSelectedRowKeys.value = keys
  }

  // 新增
  const handleAddData = () => {
    dictStore.openDataModal()
  }

  // 编辑
  const handleEditData = (record: DictData) => {
    dictStore.openDataModal(record.id)
  }

  // 提交表单
  const handleDataModalOk = async () => {
    await dictStore.submitDataForm()
  }

  // 删除
  const handleDeleteData = async (record: DictData) => {
    Modal.confirm({
      title: t('common.confirm'),
      content: t('dict.deleteDataConfirm'),
      okText: t('common.confirm'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      async onOk() {
        await dictStore.removeData(record.id)
      }
    })
  }

  // 批量删除
  const handleBatchDeleteData = async () => {
    if (dataSelectedRowKeys.value.length === 0) {
      return
    }
    Modal.confirm({
      title: t('common.confirm'),
      content: t('dict.batchDeleteConfirm'),
      okText: t('common.confirm'),
      okType: 'danger',
      cancelText: t('common.cancel'),
      async onOk() {
        const success = await dictStore.batchRemoveData(dataSelectedRowKeys.value as string[])
        if (success) {
          dataSelectedRowKeys.value = []
        }
      }
    })
  }

  // ------------ 初始化 ------------
  onMounted(() => {
    loadTypeData()
  })

  // ------------ 返回结果 ------------
  return {
    // 基础状态
    activeTab,
    currentDictType,
    currentDictTypeName,
    
    // 字典类型状态
    typeList,
    typeLoading,
    typePagination,
    typeSelectedRowKeys,
    typeQueryParams,
    typeModalVisible,
    typeSubmitLoading,
    typeFormTitle,
    typeFormData,
    typeFormRef,
    typeLoadError,
    typeErrorMessage,
    createTimeRange,
    typeSearchForm,
    
    // 字典数据状态
    dataList,
    dataLoading,
    dataPagination,
    dataSelectedRowKeys,
    dataQueryParams,
    dataModalVisible,
    dataSubmitLoading,
    dataFormTitle,
    dataFormData,
    dataFormRef,
    dataLoadError,
    dataErrorMessage,
    dataSearchForm,
    
    // 字典类型方法
    handleTypeSearch,
    resetTypeSearch,
    handleTypeTableChange,
    onTypeSelectChange,
    handleAddType,
    handleEditType,
    handleTypeModalOk,
    handleDeleteType,
    handleBatchDeleteType,
    handleExportType,
    handleViewData,
    loadTypeData,
    
    // 字典数据方法
    handleDataSearch,
    resetDataSearch,
    handleDataTableChange,
    onDataSelectChange,
    handleAddData,
    handleEditData,
    handleDataModalOk,
    handleDeleteData,
    handleBatchDeleteData,
    loadDataData
  }
} 